/**
 * @file shell_port.c
 * @author Letter (NevermindZZT@gmail.com)
 * @brief
 * @version 0.1
 * @date 2019-02-22
 *
 * @copyright (c) 2019 Letter
 *
 */

#include "shell_port.h"
#include "FreeRTOS.h"
#include "main.h"
#include "semphr.h"
#include "shell.h"
#include "task.h"
#include "usart.h"

Shell shell;
char shellBuffer[512];

static SemaphoreHandle_t shellMutex;

/**
 * @brief 用户shell写
 * @param[in] data 数据
 * @param[in] len 数据长度
 * @return 实际写入的数据长度
 */
short userShellWrite(char* data, unsigned short len)
{
    HAL_UART_Transmit(&huart1, (uint8_t*)data, len, 1000);
    uint16_t tx_len = len - huart1.TxXferCount;

    return tx_len;
}

/**
 * @brief 用户shell读
 * @param[in] data 数据
 * @param[in] len 数据长度
 * @return 实际读取到的长度
 */
short userShellRead(char* data, unsigned short len)
{
    HAL_UART_Receive(&huart1, (uint8_t*)data, len, 1000);
    uint16_t rx_len = len - huart1.RxXferCount;

    return rx_len;
}

/**
 * @brief 用户shell上锁
 * @param[in] shell shell
 * @return int 0
 */
int userShellLock(Shell* shell)
{
    xSemaphoreTakeRecursive(shellMutex, portMAX_DELAY);
    return 0;
}

/**
 * @brief 用户shell解锁
 * @param[in] shell shell
 * @return int 0
 */
int userShellUnlock(Shell* shell)
{
    xSemaphoreGiveRecursive(shellMutex);
    return 0;
}

/**
 * @brief 用户shell初始化
 */
void userShellInit(void)
{
    shellMutex = xSemaphoreCreateMutex();

    shell.write = userShellWrite;
    shell.read = userShellRead;
    shell.lock = userShellLock;
    shell.unlock = userShellUnlock;
    shellInit(&shell, shellBuffer, 512);
}
